package com.briup.xml;

import org.w3c.dom.*;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

/**
 * 构建document对象  并输出
 */
public class DocumentCreate {
    public static void main(String[] args) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.newDocument();
            //创建元素节点
            Element root = doc.createElement("root");
            Element game = doc.createElement("game");
            Element name = doc.createElement("name");
            Element plaer = doc.createElement("plaer");
            //添加属性节点
            root.setAttribute("nickName","黑大帅");
            //添加文本节点
            name.setTextContent("王者荣耀");
            //创建注释节点
            Comment comment = doc.createComment("5v5 公平竞技");
            //创建文本节点
            Text monkeyNode = doc.createTextNode("猴王");
            //创建属性节点
            Attr catchWord = doc.createAttribute("口号");
            catchWord.setValue("拉满了");



            //组装
            plaer.setAttributeNode(catchWord);
            root.appendChild(game);
            game.appendChild(name);
            doc.appendChild(root);
            game.appendChild(comment);
            game.appendChild(plaer);
            plaer.appendChild(monkeyNode);


            //输出
//  获取转换器工厂
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            //创建转换器
            Transformer transformer = transformerFactory.newTransformer();
            //设置输出属性
            transformer.setOutputProperty("indent","yes");
            transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8");

            //转换器  转换
            transformer.transform(new DOMSource(doc), new  StreamResult("C:\\Users\\sxx\\IdeaProjects\\bttc-java-basic-code\\02code\\src\\com\\briup\\xml\\file\\game.xml"));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
